# -*- coding:utf8 -*-

__author__ = 'Forcs'

import os
import json

# from moviepy.editor import VideoFileClip

from django.db import models
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render_to_response
from ftplib import FTP

from wanbatvcom.http.whttp import send_error_response_with_message, send_ok_response_with_data
from wanbatvcom import utils

def demo_upload(request):
    return render_to_response("wanplus/demo.html", {})

def do_upload(request):
    files = request.FILES

    upload_file = files['wp-upload-file']
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    upload_dir = base_dir + "/upload"
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)

    print upload_dir
    dest = open(upload_dir + "/temp_" + upload_file.name, "wb+")
    for chunk in upload_file.chunks():
        dest.write(chunk)
    dest.close()

    # clip = VideoFileClip(upload_dir + "/temp_" + upload_file.name)
    #
    # capture_dir = base_dir + "/videocapture"
    # if not os.path.exists(capture_dir):
    #     os.makedirs(capture_dir)
    #
    # clip.save_frame(capture_dir + "/" + upload_file.name + ".jpg", 10)

    ftp = FTP()
    print u'connecting to %s at %s' % ("upload.sihuacdn.com", "21")
    welcome_msg = ftp.connect("upload.sihuacdn.com", "21")
    print welcome_msg
    login_msg = ftp.login("wanbatv", "wanbatv_upload")
    print login_msg
    file_handler = open(upload_dir + "/temp_" + upload_file.name, "rb")
    print u'update %s at dir %s' % ("/temp_" + upload_file.name, upload_dir)
    ftp.storbinary('STOR %s' % upload_file.name, file_handler, 8 * 1024 * 1024)
    print u'update finish'
    file_handler.close()
    ftp.quit()
    print u'ftp quit'
    return HttpResponse("Upload Ok!")


def index(request):
    return render_to_response("wanplus/index.html", {})

def channel_list(request):
    result = dict()
    result['resultCode'] = 1
    result['message'] = ""
    data = dict()
    channel_list = list()
    channel_list.append('http://www.wanbatv.com/dogtv/DOGR1001_H264_16-9_1920x1080_2000000bps.TS')
    channel_list.append('http://www.wanbatv.com/dogtv/DOGR1002_H264_16-9_1920x1080_2000000bps.TS')
    channel_list.append('http://www.wanbatv.com/dogtv/DOGR1003_H264_16-9_1920x1080_2000000bps.TS')
    channel_list.append('http://www.wanbatv.com/dogtv/DOGR1007_H264_16-9_1920x1080_2000000bps.TS')
    data['list'] = channel_list
    result['data'] = data

    return HttpResponse(json.dumps(result), content_type="application/json")

def dump_table(request, app, table_name):

    db_table = "wanplus_{}".format(table_name)
    module = __import__("wanplus.models.{}".format(app), {}, {}, [app])

    model_name = None

    for key in module.__dict__:
        model = module.__dict__[key]
        if hasattr(model, "_meta"):
            if model._meta.db_table == db_table:
                model_name = model.__name__
                break

    if model_name is None:
        return send_error_response_with_message(message=u'应用 %s 不存在 %s 表' % (app, table_name))

    model_class = getattr(module, model_name)
    qs = model_class.objects.all()
    data_list = list()
    if qs.exists():
        try:
            data_list = list()
            for item in qs:
                data_list.append(item.to_json())

        except Exception as e:
            return send_error_response_with_message(message=u'查询 %s 表时发生了异常' % table_name)

    message = u''
    if len(data_list) == 0:
        message = u'%s 表为空' % table_name

    return send_ok_response_with_data({
        "list": data_list
    }, message=message)


def handle_upload(request):
    files = request.FILES
    if utils.upload_file(files['upload_file'], '/wangwangba'):
        return send_ok_response_with_data(data={
            "msg": True
        }, message=u'上传成功')
    else:
        return send_error_response_with_message(message=u'上传失败')


def app_upgrader(request):
    from config import BASE_PATH
    return render_to_response(BASE_PATH + "app_upgrader.html", {})


